package www.openteam.com.ui.business;

import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;

import com.cundong.recyclerview.EndlessRecyclerOnScrollListener;
import com.cundong.recyclerview.HeaderAndFooterRecyclerViewAdapter;
import com.mobsandgeeks.saripaar.Validator;
import com.throrinstudio.android.common.libs.validator.Form;
import com.throrinstudio.android.common.libs.validator.Validate;
import com.throrinstudio.android.common.libs.validator.validator.NotEmptyValidator;

import java.util.ArrayList;
import java.util.Calendar;

import butterknife.Bind;
import www.openteam.com.R;
import www.openteam.com.adapter.CustomOrderAdapter;
import www.openteam.com.base.mBaseFragment;
import www.openteam.com.bean.ApprovalStatu;
import www.openteam.com.bean.CustomOrder;
import www.openteam.com.bean.CustomType;
import www.openteam.com.bean.PackTypeInfo;
import www.openteam.com.bean.PbProductInfo;
import www.openteam.com.bean.SomeCustomInfo;
import www.openteam.com.contract.business.QueryCustomOrderInfoContract;
import www.openteam.com.presenter.business.QueryCustomOrderInfoPresenter;
import www.openteam.com.rewrite.MNotEmptyValidator;
import www.openteam.com.tool.RecyclerViewStateUtils;
import www.openteam.com.tool.ToastUtil;
import www.openteam.com.ui.DetailedActivity;
import www.openteam.com.widget.LoadingFooter;

/**
 * 编辑客户订单
 * Created by hyd on 2016/10/16.
 */

public class QueryCustomOrderInfoFragment extends mBaseFragment<QueryCustomOrderInfoPresenter>
        implements QueryCustomOrderInfoContract.QueryCustomOrderInfoView {

    private ArrayList<CustomOrder.DataEntity> editCustomOrderInfos;
    private ArrayList<CustomOrder.DataEntity> editCustomOrders;
    private static int pageSize = 0;
    private final String TAG = QueryCustomOrderInfoFragment.class.getSimpleName();
    int i = 0;
    private HeaderAndFooterRecyclerViewAdapter mFooterRecyclerViewAapter = null;
    private CustomOrderAdapter editCustomOrderAdapter = null;
    Throwable throwable = null;
    FragmentManager fm;
    private ButtonInterface buttonInterface;
    @Bind(R.id.query_btn)
    Button query;
    @Bind(R.id.tv_1)
    TextView tv_1;
    @Bind(R.id.tv_2)
    TextView tv_2;
    @Bind(R.id.ed_1)
    TextView ed_1;
    @Bind(R.id.ed_2)
    TextView ed_2;
    @Bind(R.id.floatingbar)
    ImageButton floatbar;
    private AlertDialog alertDialog;
    private EditText rdsno,customno,salesman
            ,alreadlypay,infoamout,inputdate,takegoods,orderdate,taxrate,invtype,stype,remark;
    private TextView customname;
    private Spinner istax,moneyname,payname,sendname;
    private OnClickJump onClickJump;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        detailGather = ((DetailedActivity) getActivity()).getDetailGather();
        fm = getActivity().getSupportFragmentManager();
    }


    public interface OnClickJump{
        void jumpToChild(CustomOrder.DataEntity dataEntity,boolean isInspect);
    }

    public void setOnClickJump(OnClickJump onClickJump) {
        this.onClickJump = onClickJump;
    }

    /**
     * 设置Adapter
     */
    private void setEditCustomOrderInfoAdapter() {
        if (editCustomOrderAdapter == null) {
            editCustomOrderAdapter = new CustomOrderAdapter(getActivity());
            editCustomOrderAdapter.addContext(getContext());
            mFooterRecyclerViewAapter = new HeaderAndFooterRecyclerViewAdapter(editCustomOrderAdapter);
            mRecyclerView.setAdapter(mFooterRecyclerViewAapter);
        } else {
            mFooterRecyclerViewAapter.notifyDataSetChanged();
        }
        RecyclerViewStateUtils.setFooterViewState(this.mRecyclerView, LoadingFooter.State.Normal);
        editCustomOrderAdapter.addItems(editCustomOrderInfos);
        editCustomOrderAdapter.buttonSetOnclick(new CustomOrderAdapter.ButtonInterface() {
            @Override
            public void onclickSearch(int mark, int position) {
                buttonInterface.onclickSearch(mark, position);
            }

            @Override
            public void onClickNewBuild() {
                buttonInterface.onClickNewBuild();
            }

            @Override
            public void updateSucces() {
                onRefresh();
            }

            @Override
            public void onclickSearchCustom() {
                buttonInterface.onclickSearchCustom();
            }

            @Override
            public void onclickSearchCopay() {
                buttonInterface.onclickSearchCopayName();
            }

            @Override
            public void onclickSearchPackType() {
                buttonInterface.onclickSearchPackType();
            }

            @Override
            public void onclickSearchMoneyName() {
                buttonInterface.onclickSearchMoneyName();
            }

            @Override
            public void onclickSearchSendName() {
                buttonInterface.onclickSearchSendName();
            }
        });
        editCustomOrderAdapter.setIonClickListenter(new CustomOrderAdapter.IonClickListenter() {
            @Override
            public void onClickModify(int postion) {
                //父订单修改
                showDialog(editCustomOrderInfos.get(postion));
            }

            @Override
            public void onClickCardView(int postion,boolean isInstpect) {
                //跳转到子订单
                if (onClickJump!=null){
                    onClickJump.jumpToChild(editCustomOrderInfos.get(postion),isInstpect);
                }
            }
        });

    }


    @Override
    public void onRefresh() {
        if ((mRecyclerView.getChildCount() > 0) && (!getRdsno().isEmpty()
                || !getCustid().isEmpty())) {
            Log.d(TAG, "onRefresh: " + mRecyclerView.getChildCount());
            mRecyclerView.removeAllViews();
            editCustomOrderInfos.clear();
            editCustomOrderAdapter = null;
            editCustomOrders.clear();
            mFooterRecyclerViewAapter = null;
            mPresenter.queryCustomOrderInfo(getRdsno(), getCustid(), 0);
            throwable = null;
            i = 0;
            mSwipeRefresh.setRefreshing(false);
        } else if ((mRecyclerView.getChildCount() <= 0) && (!getRdsno().isEmpty() || !getCustid().isEmpty())) {
            Log.d(TAG, "onRefresh: else if " + mRecyclerView.getChildCount());
            mRecyclerView.removeAllViews();
            editCustomOrderAdapter = null;
            editCustomOrderInfos.clear();
            editCustomOrders.clear();
            i = 1;
            mPresenter.queryCustomOrderInfo(getRdsno(), getCustid(), 0);
            mSwipeRefresh.setRefreshing(false);
        } else if ((mRecyclerView.getChildCount() >= 0) && (
                mRecyclerView != null) && (mSwipeRefresh != null)) {

            mRecyclerView.removeAllViews();
            editCustomOrderAdapter = null;
            editCustomOrderInfos.clear();
            editCustomOrders.clear();
            i = 1;
            mPresenter.queryCustomOrderInfo(getRdsno(), getCustid(), 0);
            mSwipeRefresh.setRefreshing(false);
        }
    }


    public EndlessRecyclerOnScrollListener mOnScrollListener = new EndlessRecyclerOnScrollListener() {

        @Override
        public void onLoadNextPage(View view) {
            super.onLoadNextPage(view);
            LoadingFooter.State state = RecyclerViewStateUtils.getFooterViewState(mRecyclerView);
            if (state == LoadingFooter.State.Loading) {
                Log.d("@Cundong", "the state is Loading, just wait..");
                i++;
            }
            i++;
            if (throwable == null && (editCustomOrderInfos.size() % 10 == 0)) {

                queryCondition = ((DetailedActivity) getActivity()).getQueryConditionT(); //得到选择的时间
                editCustomOrderInfos = new ArrayList<CustomOrder.DataEntity>();
                mPresenter.queryCustomOrderInfo(queryCondition.getRdsno(), queryCondition.getCode(), i);
                RecyclerViewStateUtils.
                        setFooterViewState(getActivity(), mRecyclerView, REQUEST_COUNT, LoadingFooter.State.Loading, null);
            } else if (throwable == null && (editCustomOrderInfos.size() % 10 != 0)) {
                //the end
                Log.d(TAG, "onLoadNextPage:  !-9 ");
                mPresenter.queryCustomOrderInfo(queryCondition.getRdsno(), queryCondition.getCode(), i);
                RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView, REQUEST_COUNT, LoadingFooter.State.TheEnd, null);
                throwable = null;
            } else if (throwable != null) {
                //the end
                i = 0;
                if (throwable.toString().equals("com.google.gson.JsonSyntaxException:java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 42 path $.data")) {
                    Log.d(TAG, "onLoadNextPage:  bunull ");
                    RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView, REQUEST_COUNT, LoadingFooter.State.TheEnd, null);
                    throwable = null;
                }
            }

        }
    };


    private View.OnClickListener mFooterClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView, REQUEST_COUNT, LoadingFooter.State.Loading, null);
            mPresenter.queryCustomOrderInfo(queryCondition.getRdsno(), queryCondition.getCustid(), i);
        }
    };

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        tv_1.setText(detail[0]);
        tv_2.setText(detail[1]);
        initSRView(view);
        mRecyclerView.addOnScrollListener(mOnScrollListener);
        measurementLayoutHeight();
    }


    @Override
    public String getCustid() {
        return ed_2.getText().toString();
    }

    @Override
    public String getRdsno() {
        return ed_1.getText().toString();
    }

    //取得父订单数据
    @Override
    public void loadCOIData(CustomOrder customOrder) {

        mProgressDialog.dismiss();
        for (CustomOrder.DataEntity pi : customOrder.getData()) {
            editCustomOrderInfos.add(pi);
            editCustomOrders.add(pi);
        }
        setEditCustomOrderInfoAdapter();
    }

    @Override
    public void hideCOIData(Throwable throwable) {
        this.throwable = throwable;
        mProgressDialog.dismiss();
        ToastUtil.showToast(getActivity(), throwable.getMessage());
//        RecyclerViewStateUtils.setFooterViewState(getActivity(), mRecyclerView, REQUEST_COUNT, LoadingFooter.State.TheEnd, null);
    }

    //主订单更新成功
    @Override
    public void updateCOIData(ApprovalStatu updateState) {
        mProgressDialog.dismiss();
    }

    //主订单插入成功
    @Override
    public void insertCOIData(ApprovalStatu updateState) {
        ToastUtil.showToast(getContext(),"更新成功");
        mProgressDialog.dismiss();
    }


    @Override
    protected void initData() {

    }

    @Override
    protected void initListener() {
        floatbar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialog(null);
            }
        });
    }

    @Override
    protected void initView() {
        query = (Button) view.findViewById(R.id.query_btn);
        query.setOnClickListener(new View.OnClickListener() {  //查询按钮
            @Override
            public void onClick(View v) {
                if (editCustomOrderAdapter == null) {
                    createProgressDialog(getResources().getString(R.string.querying));
                    queryCondition = ((DetailedActivity) getActivity()).getQueryConditionT(); //得到选择的时间
                    editCustomOrderInfos = new ArrayList<CustomOrder.DataEntity>();
                    editCustomOrders = new ArrayList<CustomOrder.DataEntity>();
                    mPresenter.queryCustomOrderInfo(
                            queryCondition.getRdsno(), queryCondition.getCode(), pageSize);
                } else {
                    editCustomOrderAdapter.deleteItems(editCustomOrderInfos);
                    mRecyclerView.removeAllViews();
                    editCustomOrders.clear();
                    throwable = null;
                    i = 0;
                    editCustomOrderInfos.clear();
                    onRefresh();
                }
            }
        });
    }

    @Override
    protected void otherViewClick(View view) {
        switch (view.getId()){
            case R.id.et_order_customname://客户编号
                buttonInterface.onclickSearchCustom();
                break;
            case R.id.et_order_inputdate://输入日期
                selectCalendar(inputdate);
                break;
            case R.id.et_order_sendname://送货方式
                buttonInterface.onclickSearchSendName();
                break;
            case R.id.et_order_orderdate://接单日期
                selectCalendar(orderdate);
                break;
        }
        ((DetailedActivity) getActivity()).searchFragmentClickEvent(new DetailedActivity.SearchFragmentButton() {
            @Override
            public void searchFramentButtonClick(PbProductInfo.DataEntity data, String info) {
            }

            @Override
            public void searchPackTypeInfoClick(PackTypeInfo.DataEntity dataEntity, String info) {

            }

            @Override
            public void searchCustomInfoClick(SomeCustomInfo.DataEntity dataEntity) {
                customno.setText(dataEntity.getCode());
                customno.setTag(dataEntity.getCode());
                customname.setText(dataEntity.getName());
                customname.setTag(dataEntity.getName());
                stype.setText(dataEntity.getTypename());
                stype.setTag(dataEntity.getType());
//                payname.setText(dataEntity.getPayname());
//                payname.setTag(dataEntity.getPaytime());
//                moneyname.setTag(dataEntity.getMoneytype());
//                moneyname.setText(dataEntity.getMoneyname());
            }

            @Override
            public void searchComtomTypeInfoClick(CustomType.DataBean customType, int type) {
//                if (editCustomOrderAdapter != null) {
//                    editCustomOrderAdapter.addPMCData(customType, type);
//                }
//                switch (type) {
//                    case 0:
//                        moneyname.setText(customType.getName());
//                        moneyname.setTag(customType.getCode());
//                        break;
//                    case 1:
//                        payname.setText(customType.getName());
//                        payname.setTag(customType.getCode());
//                        break;
//                    case 2:
//                        stype.setText(customType.getName());
//                        stype.setTag(customType.getCode());
//                        break;
//                    case 3:
//                        sendname.setText(customType.getName());
//                        sendname.setTag(customType.getCode());
//                        break;
//                }
            }


        });
    }
    public void selectCalendar(final TextView v){
        Calendar calendar = Calendar.getInstance();
        DatePickerDialog datePickerDialog = new DatePickerDialog(getContext(), new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                v.setText(year+"-"+(monthOfYear+1)+"-"+dayOfMonth);
            }
        }, calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH));
        datePickerDialog.show();
    }
    /**
     * 对话框
     * @param dataEntity
     */
    private void showDialog(@Nullable final CustomOrder.DataEntity dataEntity) {
        View dialog = getActivity().getLayoutInflater().inflate(R.layout.dialog_query_custom_info,
//                (ViewGroup) view.findViewById(R.id.ll_main_et)
                null
        );
        rdsno = (EditText) dialog.findViewById(R.id.et_order_rdsno);//订单编号
        customno = (EditText) dialog.findViewById(R.id.et_order_customno);//客户编号
        customname = (TextView) dialog.findViewById(R.id.et_order_customname);//客户名称
        moneyname = (Spinner) dialog.findViewById(R.id.et_order_moneyname);//常用币别
        payname = (Spinner) dialog.findViewById(R.id.et_order_payname);//付款方式
        sendname = (Spinner) dialog.findViewById(R.id.et_order_sendname);//送货方式
        salesman = (EditText) dialog.findViewById(R.id.et_salesman);//业务员
        alreadlypay = (EditText) dialog.findViewById(R.id.et_order_alreadlypay);//预付金额
        infoamout = (EditText) dialog.findViewById(R.id.et_order_infoamout);//信息额度
        inputdate = (EditText) dialog.findViewById(R.id.et_order_inputdate);//输入日期
        takegoods = (EditText) dialog.findViewById(R.id.et_order_takegoods);//送货地址
        orderdate = (EditText) dialog.findViewById(R.id.et_order_orderdate);//接单日期
        taxrate = (EditText) dialog.findViewById(R.id.et_order_taxrate);//税率
        invtype = (EditText) dialog.findViewById(R.id.et_order_invtype);//发票种类
        stype = (EditText) dialog.findViewById(R.id.et_order_stype);//单据类别
        remark = (EditText) dialog.findViewById(R.id.et_order_remark);//备注
        istax = (Spinner) dialog.findViewById(R.id.sp_order_istax);//是否含税
        final Form form = new Form();
        addNotEmptyWidget(form,customno);
        addNotEmptyWidget(form,customname);
        addNotEmptyWidget(form,salesman);
        addNotEmptyWidget(form,inputdate);
        addNotEmptyWidget(form,orderdate);
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        ArrayAdapter<String> payAdapter = new ArrayAdapter<>(getContext(),
                android.R.layout.simple_spinner_dropdown_item, payTypes);
        payAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        payname.setAdapter(payAdapter);
        ArrayAdapter<String> moneryAdapter = new ArrayAdapter<String>(getContext(),
                android.R.layout.simple_spinner_dropdown_item, moneryTypes);
        moneryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        moneyname.setAdapter(moneryAdapter);

        ArrayAdapter<String> sendAdapter = new ArrayAdapter<>(getContext(),
                android.R.layout.simple_spinner_dropdown_item, sendTypes);
        sendAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        sendname.setAdapter(sendAdapter);
        customname.setOnClickListener(this);
        inputdate.setOnClickListener(this);
        orderdate.setOnClickListener(this);
//        moneyname.setAdapter(new ArrayAdapter<String>());
//        sendname.setOnClickListener(this);
        if (null==dataEntity){
            //新建
            builder.setTitle("新建");
        }else{
            //修改
            builder.setTitle("修改");
            rdsno.setText(dataEntity.getRdsno());
            customno.setText(dataEntity.getCustid());
            customno.setTag(dataEntity.getCustid());
            customname.setText(dataEntity.getCustname());
//            moneyname.setSelection(dataEntity.getMoneyname(),true);
//            moneyname.setTag(dataEntity.getMoneytype());
//            payname.setText(dataEntity.getPayname());
//            payname.setTag(dataEntity.getPaytime());
//            sendname.setText(dataEntity.getSendname());
//            sendname.setTag(dataEntity.getSendtype());
            salesman.setText(dataEntity.getInputer());
            alreadlypay.setText(dataEntity.getAlreadlypay());
            infoamout.setText(dataEntity.getOrderamount());
            inputdate.setText(dataEntity.getInputdate());
            takegoods.setText(dataEntity.getSendaddress());
            orderdate.setText(dataEntity.getOrderdate());
            taxrate.setText(dataEntity.getTaxrate());
            invtype.setText(dataEntity.getInvtype());
            stype.setText(dataEntity.getStype());
            stype.setTag(dataEntity.getStype());
            remark.setText(dataEntity.getRemark());
            istax.setSelection(dataEntity.getIstax(),true);
        }
        builder.setPositiveButton(R.string.queding,null);
        builder.setNegativeButton(R.string.quxiao, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        builder.setView(dialog);
        alertDialog = builder.create();
        alertDialog.show();
        alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean isValidate = form.validate();
                if (isValidate){//验证通过
                    if (dataEntity==null){
                        //新建
                        mPresenter.insertCustomOrderMainInfo(customno.getText().toString(),
                                salesman.getText().toString(), mySetting.getInt("mId", 0) + "",
                                moneyTypesclass.get(moneyname.getSelectedItemPosition()).getCode(),
                                payTypesclass.get(payname.getSelectedItemPosition()).getCode(),
                                sendTypesclass.get(sendname.getSelectedItemPosition()).getCode(), "",
                                alreadlypay.getText().toString(),
                                inputdate.getText().toString(),
                                mySetting.getString("mName", ""), "0",
                                remark.getText().toString(),
                                orderdate.getText().toString(),
                                takegoods.getText().toString(),
                                istax.getSelectedItemPosition() + "",
                                taxrate.getText().toString(),
                                invtype.getText().toString(),
                                stype.getText().toString());
                    }else {
                        //修改payTypes =
                        mPresenter.updateCustomOrderMainInfo(
                                dataEntity.getId(), rdsno.getText().toString(),
                                customno.getTag().toString(), dataEntity.getUserid() + "",
                                moneyTypesclass.get(moneyname.getSelectedItemPosition()).getCode(),
                                payTypesclass.get(payname.getSelectedItemPosition()).getCode(),
                                sendTypesclass.get(sendname.getSelectedItemPosition()).getCode(),
                                dataEntity.getCustorderid(),
                                alreadlypay.getText().toString(),
                                inputdate.getText().toString(),
                                "01", 0 + "", remark.getText().toString(),
                                orderdate.getText().toString(),
                                takegoods.getText().toString(),
                                istax.getSelectedItemPosition() + "",
                                taxrate.getText().toString(),
                                invtype.getText().toString(),
                                stype.getText().toString()
                        );
                    }
                    createProgressDialog();
                    alertDialog.dismiss();
                }else {//验证不通过

                }
//                createProgressDialog();

            }
        });


    }

    private void addNotEmptyWidget(Form form, TextView view) {
        Validate notEmpty = new Validate(view);
        notEmpty.addValidator(new MNotEmptyValidator(getContext(),R.string.notempty));
        form.addValidates(notEmpty);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {

        //返回查询所得的数据

        if (null!=alertDialog){
            if (hidden){
                alertDialog.hide();
            }else {
                alertDialog.show();
            }
        }
    }

    private void createProgressDialog() {

        mProgressDialog = new ProgressDialog(getContext());
        mProgressDialog.setMessage("...正在更新,请您稍等...");
        mProgressDialog.show();
    }
    @Override
    protected QueryCustomOrderInfoPresenter loadPresenter() {
        return new QueryCustomOrderInfoPresenter();
    }

    @Override
    public void initSRView(View view) {
        super.initSRView(view);
        mSwipeRefresh = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_widget);
        mSwipeRefresh.setColorSchemeResources(R.color.colorPrimary, R.color.colorPrimaryDark, R.color.colorAccent);
        mSwipeRefresh.setOnRefreshListener(this);


        mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerview);
        linearLayoutManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(linearLayoutManager);

    }


    /**
     * 按钮点击事件需要的方法
     */
    public void buttonSetOnclick(ButtonInterface buttonInterface) {
        this.buttonInterface = buttonInterface;
    }

    /**
     * 按钮点击事件对应的接口
     */
    public interface ButtonInterface {
        void onclickSearch(int mark, int position);

        void onClickNewBuild();

        void onclickSearchPackType();

        void onclickSearchCustom();

        void onclickSearchMoneyName();

        void onclickSearchCopayName();

        void onclickSearchStypeName();

        void onclickSearchSendName();
    }

}
